<?php

namespace App\Http\Imports\Pro;

use App\Models\Material;
use App\Models\PointStick;
use App\Models\ProBom;
use App\Models\ProBomDetail;
use App\Repositories\ProBomRepository;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithColumnLimit;
use App\Models\Dic;

class BomImport implements ToCollection, WithColumnLimit
    {
    /**
     * @param Collection $collection
     */
    public function endColumn() : string
        {
        // 返回你想要限制的列数
        return 'G';
        }
    public function collection(Collection $collection)
        {
        set_time_limit(0);
        $collection->filter(function ($v, $k)
            {
            if ($k == 0) {
                return;
                }
            $code                = $v['0'];
            $material_name       = $v['1'];
            $percent             = $v['2'];
            $craft_category_name = $v['3'];
            $point_stick_name    = $v['4'];
            $glue_name           = $v['5'];
            $process_name        = $v['6'];

            $bom_m = ProBom::firstOrCreate(['code' => $code]);
            if (Material::whereName($material_name)->count() == 1)
                $material_m = Material::whereName($material_name)->first();
            else {
                fail("上传失败！{$material_name}物料未找到！");
                }
            $craft_category_m = Dic::whereCode('CraftCategory')->whereName($craft_category_name)->first();
            if ($craft_category_m == null) {
                fail("上传失败！{$craft_category_name}分类未找到！");
                }
            if (PointStick::whereName($point_stick_name)->count() == 1) {
                $point_stick_m = PointStick::whereName($point_stick_name)->first();
                }
            else {
                fail("上传失败！{$point_stick_name}点棍未找到或者重复！");
                }

            if (Material::whereName($glue_name)->count() == 1)
                $glue_m = Material::whereName($glue_name)->first();
            else {
                fail("上传失败！{$glue_name}胶水未找到！");
                }
            $bom_m->craft_category_id = $craft_category_m->key;
            $bom_m->name              = $bom_m->name . (($bom_m->name ?? "") == "" ? "" : "+") . "{$material_m->name}+{$point_stick_m->name}+{$glue_m->name}";
            $bom_m->save();
            ProBomDetail::create(
                [
                    'main_id'        => $bom_m->id,
                    'material_id'    => $material_m->id,
                    'rate'           => $percent,
                    'point_stick_id' => $point_stick_m->id,
                    'glue_id'        => $glue_m->id,
                    'process_name'   => $process_name
                ]
            );
            });

        }
    }
